//app.js
var util = require("/utils/util.js")
App({
  globalData: {
    sessionId: "sessionKey",
    wxCode: "",
    openid: "",
    unionid: "",
    apiUrl:'https://miniprogram.gksaas.cn'
  },
  onLaunch: function (options) {
    this.wxlogIn();
  },
  //小程序自带登录接口获取code
  wxlogIn: function () {
    var _this = this;
    wx.login({
      success: function (res) {
        _this.globalData.wxCode = res.code
        _this.getOpenId(_this.globalData.wxCode)
        // console.log(_this.globalData.wxCode)
      }
    });
  },
  //code换区openid和unionid
  getOpenId: function (code) {
    var _this = this;
    wx.request({
      url: _this.globalData.apiUrl+'/mobileOfficing/wechat/user/code2session?code=' + code,

      header: {
        'content-type': 'application/json;charset=UTF-8'
      },
      success: function (res) {
        // console.log(res.data)
        if(res.data.result){
          _this.globalData.openid = res.data.data.openid
          _this.globalData.unionid = res.data.data.unionid
        }
      }
    })
  },
  //判断sessionId是否合法公用方法
  request: function (options){
    wx.request({
      url: options.url,
      method: options.method || "POST",
      header: options.header || {},
      data: options.data || {},
      dataType: options.dataType || "json",
      complete: options.complete || options.fail || function (res) {
        var statusCode = res.statusCode;
        switch (statusCode) {
          case 403: {//sessionId为空或非法
            //提示
            wx.showModal({
              title: '提示',
              //content: res.data.msg,
              content: '请重新登录',
              showCancel: false,
              success: function (res) {
                //跳转到登录页
                console.log(util.getCurrentPageUrl())
                wx.redirectTo({
                  url: '/pages/logIn/logIn?source=' + util.getCurrentPageUrl()
                })
              }
            })
          } break
        }
      },
      success: options.success || new Function(),
      fail: options.fail || new Function()
    })
  }
})
